#include "Cursor.h"

Cursor::Cursor(RenderWindow &app) : app(app) {
    // load cursor image
    Image *image = new Image();
    image->LoadFromFile("gfx/cursor.png");
    sprite.SetImage(*image);

    // center mouse initially (+ hide actual cursor)
    pos = Vector2i(app.GetWidth()/2, app.GetHeight()/2);
    oldPos = pos;
    app.SetCursorPosition(pos.x, pos.y);
    app.ShowMouseCursor(false);

    enabled = true;
}

Cursor::~Cursor() {
}

void Cursor::Enable() {
    enabled = true;
    app.ShowMouseCursor(false);
}

void Cursor::Disable() {
    enabled = false;
    app.ShowMouseCursor(true);
}

Vector2i &Cursor::GetPos() {
    return pos;
}

void Cursor::HandleMouseEvent(Event event) {
    if (!enabled) return; // do nothing if disabled
    
    // move virtual position by delta distance
    Vector2i newPos(event.MouseMove.X, event.MouseMove.Y);
    pos += newPos-oldPos;
    oldPos = newPos;
}

void Cursor::Update(float dt) {
    if (!enabled) return; // do nothing if disabled

    const int width = app.GetWidth();
    const int height = app.GetHeight();

    // constrain to window
    if (pos.x < 0) {
        pos.x = 0;
    }
    else if (pos.x > width) {
        pos.x = width;
    }
    if (pos.y < 0) {
        pos.y = 0;
    }
    else if (pos.y > height) {
        pos.y = height;
    }

    // reset mouse to center
    oldPos.x = width/2;
    oldPos.y = height/2;
    app.SetCursorPosition(oldPos.x, oldPos.y);
    sprite.SetPosition(pos.x-5, pos.y-5);
}

void Cursor::Render(RenderWindow &app) {
    // draw the virtual cursor
    app.Draw(sprite);
}
